package com.yusong.algorithm.dp;

import java.util.Arrays;

public class IsInterleave97 {


    public static void main(String[] args) {

        String s2 = "bacc";
        String s1 = "aabcce";
        String s3 = "abaacbccec";
        IsInterleave97 main= new IsInterleave97();
        main.isInterleave(s1, s2, s3);
    }


    /**
     动态规划
     构造一个m * n 的表格 标记每一个点是否可达
     **/
    public boolean isInterleave(String s1, String s2, String s3) {
        int m = s1.length();
        int n = s2.length();
        int s = s3.length();
        if( s != (m + n)){
            return false;
        }
        char[] mChars = s1.toCharArray();
        char[] nChars = s2.toCharArray();
        char[] sChars = s3.toCharArray();

        //0.构造缓存，初始化第一个数据
        boolean[][] dp = new boolean[n+1][m+1];
        dp[0][0] = true;
        //初始化第一行数据
        int i = 0;
        while(mChars[i] == sChars[i] && i < m){
            dp[0][i+1] = true;
            i++;
        }
        //初始化第一列数据
        i = 0;
        while(nChars[i] == sChars[i] && i < n){
            dp[i+1][0] = true;
            i++;
        }
        System.out.println(Arrays.toString(dp[0]));
        //开始推演
        for(int j = 1; j <= n ; j++){
            for(i = 1; i <= m ; i ++){
                boolean topValue = dp[j-1][i];
                boolean leftValue = dp[j][i-1];
                char sChar = sChars[i+j -1];
                if(topValue  && (sChar == nChars[j-1])){
                    dp[j][i] = true;
                }else if(leftValue && (sChar == nChars[i-1])){
                    dp[j][i] = true;
                }else{
                    dp[j][i] = false;
                }
            }
            System.out.println(Arrays.toString(dp[j]));
        }

        return dp[n][m];
    }

}
